// API基础路径
const API_BASE_URL = 'http://localhost:8080/api/users';

// DOM元素
const userForm = document.getElementById('user-form');
const userList = document.getElementById('user-list');
const submitBtn = document.getElementById('submit-btn');
const resetBtn = document.getElementById('reset-btn');
const refreshBtn = document.getElementById('refresh-btn');
const cancelEditBtn = document.getElementById('cancel-edit-btn');
const formTitle = document.getElementById('form-title');
const loading = document.getElementById('loading');
const messageDiv = document.getElementById('message');
const userIdInput = document.getElementById('user-id');

let isEditMode = false;

// 页面加载时初始化
document.addEventListener('DOMContentLoaded', () => {
    loadUsers();
    initEventListeners();
});

// 初始化事件监听
function initEventListeners() {
    // 表单提交
    userForm.addEventListener('submit', handleFormSubmit);
    
    // 重置按钮
    resetBtn.addEventListener('click', resetForm);
    
    // 刷新按钮
    refreshBtn.addEventListener('click', loadUsers);
    
    // 取消编辑按钮
    cancelEditBtn.addEventListener('click', cancelEdit);
}

// 处理表单提交
async function handleFormSubmit(e) {
    e.preventDefault();
    
    const formData = new FormData(userForm);
    const userData = {
        username: formData.get('username'),
        email: formData.get('email'),
        password: formData.get('password')
    };
    
    try {
        if (isEditMode) {
            await updateUser(userIdInput.value, userData);
        } else {
            await createUser(userData);
        }
        showMessage('操作成功！', 'success');
        resetForm();
        loadUsers();
    } catch (error) {
        showMessage(error.message, 'error');
    }
}

// 创建用户
async function createUser(userData) {
    const response = await fetch(API_BASE_URL, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify(userData)
    });
    
    const result = await response.json();
    
    if (result.code !== 200) {
        throw new Error(result.message || '创建用户失败');
    }
    
    return result.data;
}

// 获取所有用户
async function loadUsers() {
    showLoading(true);
    try {
        const response = await fetch(API_BASE_URL);
        const result = await response.json();
        
        if (result.code === 200) {
            displayUsers(result.data || []);
        } else {
            showMessage('加载用户列表失败：' + result.message, 'error');
        }
    } catch (error) {
        showMessage('网络错误：' + error.message, 'error');
    } finally {
        showLoading(false);
    }
}

// 显示用户列表
function displayUsers(users) {
    if (users.length === 0) {
        userList.innerHTML = `
            <div class="empty-state">
                <div class="empty-state-icon">📭</div>
                <p>暂无用户数据</p>
            </div>
        `;
        return;
    }
    
    userList.innerHTML = users.map(user => `
        <div class="user-card">
            <div class="user-info">
                <div class="user-info-item">
                    <span class="user-info-label">ID</span>
                    <span class="user-info-value">#${user.id}</span>
                </div>
                <div class="user-info-item">
                    <span class="user-info-label">用户名</span>
                    <span class="user-info-value">${escapeHtml(user.username)}</span>
                </div>
                <div class="user-info-item">
                    <span class="user-info-label">邮箱</span>
                    <span class="user-info-value">${escapeHtml(user.email)}</span>
                </div>
                <div class="user-info-item">
                    <span class="user-info-label">创建时间</span>
                    <span class="user-info-value">${formatDate(user.createdAt)}</span>
                </div>
            </div>
            <div class="user-actions">
                <button class="btn-edit" onclick="editUser(${user.id})">编辑</button>
                <button class="btn-delete" onclick="deleteUser(${user.id})">删除</button>
            </div>
        </div>
    `).join('');
}

// 根据ID获取用户详情
async function getUserById(id) {
    const response = await fetch(`${API_BASE_URL}/${id}`);
    const result = await response.json();
    
    if (result.code !== 200) {
        throw new Error(result.message || '获取用户失败');
    }
    
    return result.data;
}

// 编辑用户
async function editUser(id) {
    try {
        const user = await getUserById(id);
        
        // 填充表单
        document.getElementById('username').value = user.username;
        document.getElementById('email').value = user.email;
        document.getElementById('password').value = '';
        userIdInput.value = user.id;
        
        // 切换到编辑模式
        isEditMode = true;
        formTitle.textContent = '编辑用户';
        submitBtn.textContent = '更新';
        cancelEditBtn.style.display = 'inline-block';
        
        // 滚动到表单
        document.querySelector('.form-section').scrollIntoView({ behavior: 'smooth' });
    } catch (error) {
        showMessage('获取用户信息失败：' + error.message, 'error');
    }
}

// 更新用户
async function updateUser(id, userData) {
    const response = await fetch(`${API_BASE_URL}/${id}`, {
        method: 'PUT',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify(userData)
    });
    
    const result = await response.json();
    
    if (result.code !== 200) {
        throw new Error(result.message || '更新用户失败');
    }
    
    return result.data;
}

// 删除用户
async function deleteUser(id) {
    if (!confirm('确定要删除这个用户吗？')) {
        return;
    }
    
    try {
        const response = await fetch(`${API_BASE_URL}/${id}`, {
            method: 'DELETE'
        });
        
        const result = await response.json();
        
        if (result.code === 200) {
            showMessage('用户删除成功！', 'success');
            loadUsers();
        } else {
            throw new Error(result.message || '删除用户失败');
        }
    } catch (error) {
        showMessage('删除失败：' + error.message, 'error');
    }
}

// 取消编辑
function cancelEdit() {
    resetForm();
}

// 重置表单
function resetForm() {
    userForm.reset();
    userIdInput.value = '';
    isEditMode = false;
    formTitle.textContent = '创建用户';
    submitBtn.textContent = '提交';
    cancelEditBtn.style.display = 'none';
    
    // 清除错误信息
    document.querySelectorAll('.error-message').forEach(el => {
        el.textContent = '';
    });
}

// 显示/隐藏加载状态
function showLoading(show) {
    loading.style.display = show ? 'block' : 'none';
}

// 显示消息提示
function showMessage(message, type = 'success') {
    messageDiv.textContent = message;
    messageDiv.className = `message ${type}`;
    messageDiv.style.display = 'block';
    
    setTimeout(() => {
        messageDiv.style.display = 'none';
    }, 3000);
}

// 转义HTML，防止XSS攻击
function escapeHtml(text) {
    const div = document.createElement('div');
    div.textContent = text;
    return div.innerHTML;
}

// 格式化日期
function formatDate(dateString) {
    if (!dateString) return '未知';
    const date = new Date(dateString);
    return date.toLocaleString('zh-CN');
}


